package image_utils

import (
	"fmt"
	"image"
	"image/jpeg"
	"image/png"
	"os"
	"path/filepath"
)

func CropImage(img image.Image, point1, point2 image.Point) (image.Image, error) {
	rect := image.Rect(point1.X, point1.Y, point2.X, point2.Y)
	croppedImg := img.(SubImg).SubImage(rect)

	return croppedImg, nil
}

type SubImg interface {
	SubImage(r image.Rectangle) image.Image
}

func SaveImage(filePath string, img image.Image) error {
	file, err := os.Create(filePath)
	if err != nil {
		return err
	}
	defer file.Close()

	// 根据文件扩展名选择保存格式
	ext := filepath.Ext(filePath)
	switch ext {
	case ".jpg", ".jpeg":
		return jpeg.Encode(file, img, nil)
	case ".png":
		return png.Encode(file, img)
	default:
		return fmt.Errorf("unsupported file format: %s", ext)
	}
}
